package org.xlp.db.bridge.strategy;

import org.xlp.db.xml.XmlSQL;
import org.xlp.utils.collection.XLPCollectionUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * Description: 获取{@link XmlSQL}构造信息上下文
 * <br/>date: 2024/4/24
 *
 * @version 1.0
 * @author: xlp
 */
public class XmlSQLConstructorStrategyContext {
    /**
     * 标记是否已排序
     */
    private boolean ordered = false;

    /**
     * 存储获取{@link XmlSQL}构造信息策略对象集合
     */
    private List<IXmlSQLConstructorStrategy> strategies = new ArrayList<>();

    /**
     * 添加策略对象
     * @param strategy
     */
    public void addStrategy(IXmlSQLConstructorStrategy strategy){
        if (strategy == null) return;
        ordered = true;
        strategies.add(strategy);
    }

    /**
     * 添加策略对象
     * @param strategies
     */
    public void addStrategies(List<IXmlSQLConstructorStrategy> strategies){
        if (XLPCollectionUtil.isEmpty(strategies)) return;
        ordered = true;
        this.strategies = strategies;
    }

    /**
     * 集合策略对象
     * @param strategies
     * @return 返回一个不可修改集合
     */
    public List<IXmlSQLConstructorStrategy> getStrategies(List<IXmlSQLConstructorStrategy> strategies){
        return Collections.unmodifiableList(strategies);
    }

    /**
     * 根据给定的参数类型获取相应的{@link XmlSQLConstructorInfo}对象
     * @param methodReturnType
     * @param parameterClasses
     * @param parameters
     * @return
     */
    public XmlSQLConstructorInfo getXmlSQLConstructor(Type methodReturnType, Class<?>[] parameterClasses,
                                               Object[] parameters){
        //排序
        if (ordered){
            Collections.sort(strategies);
            ordered = false;
        }
        for (IXmlSQLConstructorStrategy strategy : strategies) {
            XmlSQLConstructorInfo info = strategy.getXmlSQLConstructor(methodReturnType, parameterClasses,
                    parameters);
            if (info != null) return info;
        }
        return null;
    }

    /**
     * 添加默认的策略对象
     */
    public void addDefaultStrategies(){
        strategies.add(new XmlSQLConstructorStrategy());
        strategies.add(new LMBXmlSQLConstructorStrategy());
        strategies.add(new MBXmlSQLConstructorStrategy());
        strategies.add(new OMBXmlSQLConstructorStrategy());
        strategies.add(new ZPXmlSQLConstructorStrategy());
    }

    /**
     * 移除符合条件的策略对象
     * @param filter 移除条件
     * @return 移除成功返回true，否则返回false
     */
    public boolean removeStrategyIf(Predicate<? super IXmlSQLConstructorStrategy> filter){
        return strategies.removeIf(filter);
    }
}
